package org.example.rowing.controller;

import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import org.example.rowing.controller.raceProcessController.*;
import org.example.rowing.controller.util.BaseController;
import org.example.rowing.controller.util.NavigationUtil;
import org.example.rowing.domain.Race;
import org.example.rowing.enums.BoatTypeEnum;
import org.example.rowing.enums.GenderEnum;
import org.example.rowing.service.RaceInfoService;
import org.example.rowing.service.RaceProcessCommonService;
import org.example.rowing.vo.RaceVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import java.io.IOException;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;

@Controller
@Slf4j
public class RaceInfoController extends BaseController {

    @FXML
    public TextField searchTextField1;
    @FXML
    public TextField searchTextField2;
    @FXML
    public ComboBox genderComboBox;
    @FXML
    private VBox sideNav;

    @FXML
    private TableView<RaceVO> eventsTable;

    private ObservableList<RaceVO> eventList;

    @FXML
    private Button addRaceButton;

    @FXML
    private Button btnRaceManagement;

    public TableColumn<RaceVO, String> idColumn;
    @FXML
    private TableColumn<RaceVO, String> nameColumn;
    @FXML
    private TableColumn<RaceVO, String> eventColumn;
    @FXML
    private TableColumn<RaceVO, String> distanceColumn;
    @FXML
    private TableColumn<RaceVO, String> categoryColumn;
    @FXML
    private TableColumn<RaceVO, String> timeColumn;
    @FXML
    private TableColumn<RaceVO, String> genderColumn;
    @FXML
    private TableColumn<RaceVO, Void> operationColumn;

    @Autowired
    private RaceInfoService raceInfoService;
    @Autowired
    private RaceProcessCommonService raceProcessCommonService;

    @Override
    protected Button getButton() {
        return btnRaceManagement;
    }

    @Override
    public void initialize() {
        super.initialize();

        // 设置表格列
        idColumn.setCellValueFactory(cellData -> new SimpleStringProperty(String.valueOf(cellData.getValue().getId())));
        nameColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getName()));
        eventColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getEventVO().getName()));
        distanceColumn.setCellValueFactory(cellData -> new SimpleStringProperty(String.valueOf(cellData.getValue().getDistance())));
        categoryColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getRaceType()));
        timeColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getRaceDate()));
        genderColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getGenderEnum().getDisplayName()));

        // 设置操作列（修改、删除按钮）
        operationColumn.setCellFactory(col -> new TableCell<>() {
            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setGraphic(null);
                } else {
                    Button modifyButton = new Button("修改");
                    modifyButton.setOnAction(event -> handleModifyEvent(getTableRow().getItem()));

                    Button deleteButton = new Button("删除");
                    deleteButton.setOnAction(event -> handleDeleteEvent(getTableRow().getItem()));

                    Button watchButton = new Button("查看");
                    watchButton.setOnAction(event -> {
                        try {
                            handleWatchEvent(getTableRow().getItem());
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    });

                    HBox hBox = new HBox(modifyButton, deleteButton, watchButton);
                    setGraphic(hBox);
                }
            }
        });

        // 初始化赛事列表（默认展示一些数据）
        eventList = FXCollections.observableArrayList(raceInfoService.showRacesByBoatType(BoatTypeEnum.ROWING.getDisplayName()));
        eventsTable.setItems(eventList);
    }

    @FXML
    private void handleNavButtonClick(ActionEvent event) throws IOException {
        log.info("当前触发事件为：{}",event);
        Button clickedButton = (Button) sideNav.getScene().getFocusOwner();
        NavigationUtil.navigateToScene(
                event,
                NavigationUtil.viewMap.get(clickedButton.getId()),
                "赛艇管理");
    }

    @FXML
    public void handleSearch() {
        String nameQuery = searchTextField1.getText().trim();  // 获取输入的比赛名称
        String eventQuery = searchTextField2.getText().trim();  // 获取输入的赛事名称
        Object genderComboBoxValue = genderComboBox.getValue();

        log.info("搜索栏内容为：{} {} {}", nameQuery, eventQuery, genderComboBoxValue);

        RaceVO race = new RaceVO();
        race.setBoatType(BoatTypeEnum.ROWING.getDisplayName());
        if (!nameQuery.isEmpty()) {
            race.setName(nameQuery);
        }
        if (!eventQuery.isEmpty()) {
            race.setEventName(eventQuery);
        }
        if (genderComboBoxValue != null) {
            race.setGenderEnum((GenderEnum.fromDisplayName((String) genderComboBoxValue)));
        }

        // 将过滤后的列表更新到表格
        eventList.setAll(raceInfoService.showSearchedRaces(race));
        eventsTable.refresh();
    }

    @FXML
    public void handleClearSearch() {
        // 清空搜索框内容
        searchTextField1.clear();
        searchTextField2.clear();
        // 清空性别选择框并重新填充
        genderComboBox.getItems().clear();  // 清空当前选项
        genderComboBox.setItems(FXCollections.observableArrayList("男子", "女子", "混合"));  // 重新填充选项

        // 重新显示所有赛事
        eventList.setAll(raceInfoService.showRacesByBoatType(BoatTypeEnum.ROWING.getDisplayName()));
        eventsTable.refresh();
    }

    // 添加赛事事件
    @FXML
    private void handleAddEvent() {
        // 打开添加赛事界面的逻辑
        log.info("点击添加比赛按钮");
        NavigationUtil.showPopup(
                NavigationUtil.viewMap.get(addRaceButton.getId()),
                "添加比赛",
                addRaceButton.getScene().getWindow(),
                controller -> {
                    if (controller instanceof UpdateRaceController) {
                        ((UpdateRaceController) controller).initialize(null);
                    }
                }
        );
        // 重新显示所有赛事
        eventList.setAll(raceInfoService.showRacesByBoatType(BoatTypeEnum.ROWING.getDisplayName()));
        eventsTable.refresh();
    }

    // 修改赛事事件
    private void handleModifyEvent(RaceVO race) {
        // 进行修改赛事操作
        log.info("修改比赛: {}", race.getName());
        NavigationUtil.showPopup(
                NavigationUtil.viewMap.get(addRaceButton.getId()),
                "修改比赛",
                eventsTable.getScene().getWindow(),
                controller -> {
                    if (controller instanceof UpdateRaceController) {
                        ((UpdateRaceController) controller).initialize(race);
                    }
                }
        );
        // 重新显示所有赛事
        eventList.setAll(raceInfoService.showRacesByBoatType(BoatTypeEnum.ROWING.getDisplayName()));
        eventsTable.refresh();
    }

    // 删除赛事事件
    private void handleDeleteEvent(RaceVO raceVO) {
        Optional<ButtonType> result = showConfirmationDialog();
        // 删除赛事操作
        if (result.isPresent() && Objects.equals(result.get().getText(), "确定")) {
            raceInfoService.deleteRace(raceVO.getId());
            log.info("删除比赛: {}", raceVO.getName());
            // 刷新展示内容
            eventList.setAll(raceInfoService.showRacesByBoatType(BoatTypeEnum.ROWING.getDisplayName()));
            eventsTable.refresh();
        } else {
            log.info("取消删除");
        }
    }

    private void handleWatchEvent(RaceVO raceVO) throws IOException {
        log.info("查看比赛: {}", raceVO.getName());
        Integer sizeOfTeams = raceProcessCommonService.sizeOfTeams(raceVO);

        // 定义变量存储 fxml 路径和初始化回调
        String fxmlPath = null;
        Consumer<Object> initializer = null;

        // 根据团队规模设置对应的 fxml 和回调逻辑
        if (sizeOfTeams == 3 || sizeOfTeams == 4 || sizeOfTeams == 5 || sizeOfTeams == 6) {
            fxmlPath = "/fxml/rowingViews/raceProcessView/lessSixView.fxml";
            initializer = controller -> {
                if (controller instanceof LessSixController) {
                    ((LessSixController) controller).initialize(raceVO);
                }
            };
        } else if (sizeOfTeams == 7 || sizeOfTeams == 8) {
            fxmlPath = "/fxml/rowingViews/raceProcessView/sevenToEightView.fxml";
            initializer = controller -> {
                if (controller instanceof SevenToEightController) {
                    ((SevenToEightController) controller).initialize(raceVO);
                }
            };
        } else if (sizeOfTeams == 9 || sizeOfTeams == 10) {
            fxmlPath = "/fxml/rowingViews/raceProcessView/nineToTenView.fxml";
            initializer = controller -> {
                if (controller instanceof NineToTenController) {
                    ((NineToTenController) controller).initialize(raceVO);
                }
            };
        } else if (sizeOfTeams == 11 || sizeOfTeams == 12) {
            fxmlPath = "/fxml/rowingViews/raceProcessView/elevenOrTwelveView.fxml";
            initializer = controller -> {
                if (controller instanceof ElevenOrTwelveController) {
                    ((ElevenOrTwelveController) controller).initialize(raceVO);
                }
            };
        } else if (sizeOfTeams == 13 || sizeOfTeams == 14 || sizeOfTeams == 15) {
            fxmlPath = "/fxml/rowingViews/raceProcessView/thirteenToFifteenView.fxml";
            initializer = controller -> {
                if (controller instanceof ThirteenToFifteenController) {
                    ((ThirteenToFifteenController) controller).initialize(raceVO);
                }
            };
        } else if (sizeOfTeams == 16 || sizeOfTeams == 17 || sizeOfTeams == 18) {
            fxmlPath = "/fxml/rowingViews/raceProcessView/sixteenToEighteenView.fxml";
            initializer = controller -> {
                if (controller instanceof SixteenToEighteenController) {
                    ((SixteenToEighteenController) controller).initialize(raceVO);
                }
            };
        } else if (sizeOfTeams >= 19) {
            fxmlPath = "/fxml/rowingViews/raceProcessView/overNineteenView.fxml";
            initializer = controller -> {
                if (controller instanceof OverNineteenController) {
                    ((OverNineteenController) controller).initialize(raceVO);
                }
            };
        } else {
            log.warn("Unhandled team size: {}", sizeOfTeams);
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("输入错误");
            alert.setHeaderText(null);
            alert.setContentText("报名该比赛的队伍数量不足3个，比赛无法开始！！！");
            alert.showAndWait();
            return;
        }

        // 统一调用弹窗展示方法
        if (raceVO.getIsLongDistance()) {
            NavigationUtil.showPopup("/fxml/LongDistanceRaceProcessView.fxml",
                    "查看比赛",
                    eventsTable.getScene().getWindow(),
                    controller -> ((LongDistanceProcessController) controller).initialize(raceVO)
            );
        } else {
            NavigationUtil.showPopup(fxmlPath, "查看比赛", eventsTable.getScene().getWindow(), initializer);
        }
    }

    // 对皮划艇菜单点击的处理
    @FXML
    public void handleBoatTypeClick(ActionEvent event) throws IOException {
        log.info("切换到皮划艇界面");
        NavigationUtil.navigateToScene(
                (Stage) sideNav.getScene().getWindow(),
                "/fxml/canoeAndKayakViews/CKEventInfoView.fxml",
                "皮划艇管理");
    }
}
